/*
    项目数据实例
 */
let baseUrl = '../'
let xlsx = require('xlsx')
class PrjData {
  constructor (code) {
    this._code = code
    this._dataDict = {}
    this._defs = []
  }
  load () {
    let workbook = xlsx.readFile(baseUrl + `static/data/${this._code}/data.xlsx`) // workbook就是xlsx文档对象
    let sheetNames = workbook.SheetNames // 获取表明
    for (let i = 0; i < sheetNames.length; i++) {
      let name = sheetNames[i]
      let list = name.split('-')
      // eslint-disable-next-line eqeqeq
      if (list.length === 3) {
        let objCode = list[2]
        let sheet = workbook.Sheets[name] // 通过表明得到表对象
        var objData = xlsx.utils.sheet_to_json(sheet) // 通过工具将表对象的数据读出来并转成json
        this._dataDict[objCode] = this.decodeData(objData)
        this._defs.push({num: list[0],code: objCode, name: list[1], def: this._dataDict[objCode].def})
      }
    }
  }
  add2Row (def, row, property) {
    for (let key in row) {
      // eslint-disable-next-line eqeqeq
      if (key != '__EMPTY') {
        // eslint-disable-next-line eqeqeq
        let find = def.find(x => x.name == key)
        if (!find) {
          find = {name: key}
          def.push(find)
        }
        find[property] = row[key]
      }
    }
  }
  decodeData (objData) {
    let def = []
    let rowNum = 0
    for (let i = 0; i < objData.length; i++) {
      let row = objData[i]
      switch (row.__EMPTY) {
        case 'Status':
        case 'Heading':
        case '<UNITS>':
        case 'TYPE':
        case 'Description':
          this.add2Row(def, row, row.__EMPTY)
          rowNum = i
          break
        default:break
      }
    }
    let dict = {}
    def.forEach(one => {
      dict[one.name] = one.Heading
    })
    let data = []
    for (let i = rowNum + 1; i < objData.length; i++) {
      let row = objData[i]
      let one = {}
      for (let key in row) {
        one[dict[key]] = row[key]
      }
      data.push(one)
    }

    return {def, data}
  }
  getDef (objCode) {
    if (objCode){
      return this._defs.find(x=>x.code==objCode);
    }else{
      return this._defs
    }

  }
  getData (objCode) {
    if (this._dataDict[objCode]) {
      return this._dataDict[objCode].data
    } else {
      return null
    }
  }
}
module.exports = PrjData
